package com.toy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.toy.entity.User;
import com.toy.entity.UserAddress;
import com.toy.exception.ToyMallException;
import com.toy.form.UserLoginForm;
import com.toy.form.UserRegisterForm;
import com.toy.mapper.UserAddressMapper;
import com.toy.result.ResponseEnum;
import com.toy.service.CartService;
import com.toy.service.OrdersService;
import com.toy.service.UserAddressService;
import com.toy.service.UserService;
import com.toy.util.RegexValidateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.ws.rs.Path;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2022-08-31
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CartService cartService;
    @Autowired
    private UserAddressService userAddressService;

    /**
     * 用户注册
     * @param userRegisterForm
     * @param bindingResult
     * @return
     */
    //UserRegisterForm对前端传过来的数据进行校验，错误信息返回给BindingResult
    @PostMapping("/register")
    public String register(@Valid UserRegisterForm userRegisterForm, BindingResult bindingResult){
        //非空校验
        if (bindingResult.hasErrors()){
            log.info("【用户注册】用户信息不能为空");
            throw new ToyMallException(ResponseEnum.USER_INFO_NULL);
        }
        this.userService.register(userRegisterForm);
        return "redirect:/login";
    }

    /**
     * 用户登录
     * @return
     */
    @PostMapping("/login")
    public String login(@Valid UserLoginForm userLoginForm, BindingResult bindingResult, HttpSession session){
        //非空校验
        if (bindingResult.hasErrors()){
            log.info("【用户登录】用户信息不能为空");
            throw new ToyMallException(ResponseEnum.USER_INFO_NULL);
        }
        User login = this.userService.login(userLoginForm);
        session.setAttribute("user", login);
        return "redirect:/productCategory/main";
    }

    /**
     * 用户注销
     * @return
     */
    @GetMapping("/logout")
    public String logOut(HttpSession session){
        session.invalidate();
        return "redirect:/login";
    }

    /**
     * 返回当前用户的订单列表
     * @return
     */
    @GetMapping("/orderList")
    public ModelAndView ordersList(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user == null){
            log.info("【我的订单】当前为未登录状态");
            throw new ToyMallException(ResponseEnum.NOT_LOGIN);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("orderList");
        modelAndView.addObject("orderList",
                this.ordersService.findAllByUserId(user.getId()));
        modelAndView.addObject("cartList",
                this.cartService.findCartVOListByUserId(user.getId()));
        return modelAndView;
    }

    /**
     * 返回当前用户的地址列表
     * @return
     */
    @GetMapping("/addressList")
    public ModelAndView addressList(HttpSession session){
        //判断是否为登录用户
        User user = (User) session.getAttribute("user");
        if(user == null){
            log.info("【我的地址】当前为未登录状态");
            throw new ToyMallException(ResponseEnum.NOT_LOGIN);
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("userAddressList");
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getId());
        modelAndView.addObject("addressList", this.userAddressService.list(queryWrapper));
        modelAndView.addObject("cartList", this.cartService.findCartVOListByUserId(user.getId()));
        return modelAndView;
    }

    /**
     * 修改用户信息
     * @param userName
     * @param email
     * @param mobile
     * @param session
     * @return
     */
    @PostMapping("/update/{userName}/{email}/{mobile}")
    @ResponseBody
    @Transactional
    public String updateInfo(
            @PathVariable("userName") String userName,
            @PathVariable("email") String email,
            @PathVariable("mobile") String mobile,
            HttpSession session){
        if (userName == null || email == null || mobile == null){
            log.info("【我的信息修改】参数为空");
            throw new ToyMallException(ResponseEnum.PARAMETER_NULL);
        }
        //判断是否为登录用户
        User user = (User) session.getAttribute("user");
        if(user == null){
            log.info("【我的信息修改】当前为未登录状态");
            throw new ToyMallException(ResponseEnum.NOT_LOGIN);
        }
        user.setUserName(userName);
        user.setEmail(email);
        user.setMobile(mobile);
        boolean b = userService.updateById(user);
        if (b){
            session.setAttribute("user", user);
            return "success";
        }
        return "fail";
    }

    /**
     * 删除用户某个地址
     * @param id
     * @return
     */
    @GetMapping("/deleteAddress/{id}")
    public String deleteAddress(@PathVariable("id") Integer id){
        userAddressService.removeById(id);
        return "redirect:/user/addressList";
    }

    /**
     * 设置默认地址
     * @param id
     * @return
     */
    @GetMapping("/updateAddress/{id}")
    public String updateAddress(@PathVariable("id") Integer id){
        userAddressService.setDefault();
        UserAddress userAddress = new UserAddress();
        userAddress.setIsdefault(1);
        userAddress.setId(id);
        userAddressService.updateById(userAddress);
        return "redirect:/user/addressList";
    }

    /**
     * 添加地址
     * @param address
     * @param remark
     * @param session
     * @return
     */
    @PostMapping("/addAddress/{address}/{remark}")
    @ResponseBody
    @Transactional
    public String addAddress(
            @PathVariable("address") String address,
            @PathVariable("remark") String remark,
            HttpSession session){
        if (address == null || remark == null){
            log.info("【我的地址添加】参数为空");
            throw new ToyMallException(ResponseEnum.PARAMETER_NULL);
        }
        //判断是否为登录用户
        User user = (User) session.getAttribute("user");
        if(user == null){
            log.info("【我的地址添加】当前为未登录状态");
            throw new ToyMallException(ResponseEnum.NOT_LOGIN);
        }
        userAddressService.setDefault();
        UserAddress userAddress = new UserAddress();
        userAddress.setUserId(user.getId());
        userAddress.setAddress(address);
        userAddress.setRemark(remark);
        userAddress.setIsdefault(1);
        boolean save = userAddressService.save(userAddress);
        if (save){
            return "success";
        }
        return "fail";
    }
}

